package cn.org.xuanzp.nty.utils;

import io.netty.channel.ChannelHandlerContext;

import java.util.HashMap;
import java.util.Map;

/**
 * @Classname NettyerClientUtil
 * @Description TODO
 * @Version 1.0.0
 * @Date 2024/9/26 23:16
 * @Created by xuanzp
 */
public class NettyClientUtil {


    private static Map<String, ChannelHandlerContext> servers = new HashMap<String, ChannelHandlerContext>();

    public static Boolean existCtx(String serverId){
        Boolean containsKey = servers.containsKey(serverId);
        if(containsKey){
            ChannelHandlerContext channelHandlerContext = servers.get(serverId);
            containsKey = (!channelHandlerContext.isRemoved()) && channelHandlerContext.channel().isActive();
        }
        return containsKey;
    }

    public static void addCtx(String serverId, ChannelHandlerContext ctx){
        servers.put(serverId, ctx);
    }

    public static void removeCtx(String serverId){
        servers.remove(serverId);
    }

    public static void send(String serverId, Object msg){
        if(!servers.containsKey(serverId)){
            System.err.println("serverId not exist");
            return;
        }
        ChannelHandlerContext ctx = servers.get(serverId);
        if(!ctx.isRemoved() && ctx.channel().isActive()){
            ctx.channel().writeAndFlush(msg);
        }else {
            System.err.println("serverId connect exception");
        }

    }
}
